/**
 * Module dependencies.
 */
const fs = require('fs')
const Router = require('koa-router')
const thunkify = require('thunkify')
const fetchExternalIp = require('externalip')
const parser = require('ua-parser-js')
const mysql = require('mysql')
const parse = require('co-body')
const mongoose = require('mongoose')
const moment = require('moment')
const uuid = require('node-uuid')
const helper = require('../modules/helper')
const Vistor = require('../models/vistor')
const Client = require('../models/client')

// connect to the mongodb
// mongoose.connect(process.env.MONGODB_CONNECTION)

// mysql connection config
const conn = mysql.createConnection({
  host: process.env.MYSQL_HOST,
  user: process.env.MYSQL_USER,
  password: process.env.MYSQL_PASSWORD,
  database: process.env.MYSQL_DATABASE,
})

const conn2 = mysql.createConnection({
  host: '122.144.199.196',
  user: 'backup',
  password: 'S8S%2Mnd^tA',
  database: 'pro_yunmall',
})

const conn3 = mysql.createConnection({
  host: '122.144.199.196',
  user: 'backup',
  password: 'S8S%2Mnd^tA',
  database: 'pro_yunsupply2',
})

const readFile = thunkify(fs.readFile)
const getIp = thunkify(fetchExternalIp)
const ipLookUp = thunkify(helper.ipLookUp)
// sqlQuery execute occured wrong
// TypeError: Cannot read property 'typeCast' of undefined
// const sqlQuery = thunkify(conn.query)
// notice the bind
const sqlQuery = thunkify(conn.query.bind(conn))

const router = new Router({
  prefix: '/v1'
})

function recordRequestClient(data) {
  data.createdAt = new RegExp((new Date()).toLocaleString().substr(0, 10))
  const query = Client.findOne(data).exec()
  query.then((rs) => {
    if (rs) {
      return
    }
    data.createdAt = (new Date()).toLocaleString()
    data.uuid = uuid.v4()
    new Client(data).save()
  }).catch((err) => {
    // this error can be ignored
  })
}

function randomDateTime() {
  var start = new Date(2016, 04, 20).getTime() / 1000
  var end = new Date(2016, 10, 18).getTime() / 1000

  var delta = end - start

  var s = '2016-04-20 00:00:00'

  var t = moment(s).format('YYYY-MM-DD HH:mm:ss')

  // console.log(`Start At ${t}`)

  var randomS = moment(s).add(Math.floor(Math.random() * delta) + 1, 'seconds').format('YYYY-MM-DD HH:mm:ss')

  // console.log(`Random T ${randomS}`)
  // console.log(randomS)
  return randomS
}

const userSchema = new mongoose.Schema({
  username: String,
  password: String,
  createdAt: Date,
  Balance: String,
  ResultCD: String,
})

const User = mongoose.model('User', userSchema)

router.get('/balance', function* () {
  this.set('Access-Control-Allow-Origin', '*')
  this.body = yield User.findOne()
  // console.log(User.find())
  // this.body = { username: 'safarishi', Balance: '10.01', ResultCD: 'I001' }
})

router.get('/', function* () {
  this.type = 'application/javascript'
  let data = yield readFile('dest/js/f.min.js', 'utf8')
  this.body = data.replace(/HOSTNAME_PORT/, this.host)
})

router.post('/vistors', function* () {
  // set cross domain access header
  this.set('Access-Control-Allow-Origin', '*')

  // parse request bodies with generators
  let data = yield parse(this)

  const productId = data.product_id
  const orderId = data.order_id

  let ip = yield getIp()
  data.ip = ip
  let district = yield ipLookUp(ip)
  data.district = district.province
  let device = ''
  let userAgent = parser(this.headers['user-agent'])
  data.user_agent = userAgent.ua
  data.browser = userAgent.browser
  let type = userAgent.device.type
  if (type === undefined) {
    device = 'pc'
  } else {
    if (/mobile mqqbrowser/i.test(userAgent.ua) && (!/ QQ\//.test(userAgent.ua))) {
      device = 'wechat mobile'
    } else {
      device = 'mobile'
    }
  }
  data.equipment = device

  const sqlStatement = 'SELECT p.id,g.seller_id FROM yunmall_products AS p LEFT JOIN yunmall_goods AS g ON p.goods_id=g.id WHERE p.id=?';
  let rs = yield sqlQuery(sqlStatement, [18])
  data.product = JSON.parse(JSON.stringify(rs[0][0]))
  if ((data.product === undefined)) {
    data.product = {
      id: productId,
    }
  }
  let orderSql = 'SELECT id,user_id,seller_id FROM yunmall_order WHERE id=?'
  let orderRs = yield sqlQuery(orderSql, [4])
  data.order = JSON.parse(JSON.stringify(orderRs[0][0]))

  let divisionData = {
    platform: data.platform,
    publicIp: ip,
    device: device
  }
  // 记录访客数 Unique Vistor
  recordRequestClient(divisionData);

  yield Vistor.create(data)

  this.status = 201
  this.body = { msg: 'success' }
})

router.get('/day/:flag', function* () {
  let flag = this.params.flag
  let sellerId = helper.parseQuerySellerId(this.query.seller_id)
  if (sellerId === false) {
    sellerId = null
  }
  let date
  if (flag === 'yesterday') {
    // 昨天的日期字符串
    date = moment().add(-1, 'day').format('YYYY-MM-DD')
  }
  else if (flag === 'today') {
    date = moment().format('YYYY-MM-DD')
  }
  else {
    this.throw(400, 'Bad Request')
  }
  let pattern = new RegExp(date)
  let rawOutput = yield Vistor.findByRegex(flag, pattern, sellerId)
  let output = helper.assembleOutput(rawOutput, flag)
  let uvOutput = yield Client.findUuidByRegex(pattern)
  output.uv = uvOutput.length

  this.jsonp = output
})

router.get('/range_within/:interval', function* () {
  let interval = this.params.interval
  let sellerId = helper.parseQuerySellerId(this.query.seller_id)
  if (sellerId === false) {
    sellerId = null
  }
  // 起始日期
  let startAt = helper.judgeStartAt(interval)
  if (startAt === '') this.throw(400, 'Bad Request')
  let date = moment().format('YYYY-MM-DD')
  let rawOutput = yield Vistor.findByRange(interval, { start: startAt, end: date }, sellerId)
  let output = helper.assembleOutput(rawOutput, interval)

  let uvOutput = yield Client.findUuidByRange({ start: startAt, end: date })
  output.uv = uvOutput.length

  this.jsonp = output
})

router.get('/pages/duration-time/:date', function* () {
  let date = this.params.date

  if (moment(date).format() === 'Invalid date') {
    this.throw(400, 'Invalid date')
  }

  let pattern = new RegExp(date)
  let output = yield Vistor.findPageDurationTimeByRegex(pattern)
  // You may only yield a function, promise, generator, array, or object,
  // but the following object was passed: undefined
  // let output = yield undefined
  // response with jsonp format
  this.jsonp = output
  // respopnse with json format
  // this.body = output
})

// via callback
router.get('/seller/username/area_id', function* () {
  // 基础数据
  // sql[SELECT id,seller_name,area,city,province FROM `yunmall_seller` where id>=50 and id<=100]
  let arr = []
  conn2.query('SELECT id,seller_name,area,city,province FROM `yunmall_seller` where id>=50 and id<=100', (err, rs) => {
    rs.forEach(v => {
      // SELECT userid,username,areaid FROM `yunsupply_member` where username="xiefu"
      const execSql = `update \`yunsupply_member\` set areaid=${v.area} where username="${v.seller_name}"`
      conn3.query(execSql, (err, r) => {
        console.log(r)
        if (r[0]) {
          console.log(r[0].areaid, typeof r[0].areaid, v.area, typeof v.area)
        }
        console.log(r, '-r', v.area, typeof v.area, r.areaid)
      })
      // arr.push({
      //   username: v.seller_name,
      //   areaId: v.area, // typeof v.area number
      // })
    })
  })
  this.body = '获取卖家 用户名 和 地区 id'
})

module.exports = router